<template>
  <div class='flex-app-continer'>
    <split-pane :min-percent='20' :default-percent='35' split='vertical' style="border: 1px solid #e8eaec">
      <template slot='paneL'>
        <div class='flex-app-continer-inner'>
          <vxe-form ref='form2' :data='formData2' @submit='querySubDept' size='mini' title-align='right'
                    title-width='100'>
            <vxe-form-item title='' field='departName' align='center' title-align='center'>
              <template v-slot>
                <vxe-input
                  v-model='formData2.departName'
                  placeholder='请输入部门名称回车查询2'
                  clearable
                ></vxe-input>
              </template>
            </vxe-form-item>

          </vxe-form>
          <vxe-toolbar  size='mini' :refresh='{ query: querySubDept }'>
            <template v-slot:buttons>
              <vxe-button status='primary' @click='$refs.xTable1.setAllTreeExpand(true)'>
                展开
              </vxe-button>
              <vxe-button status='primary' @click='$refs.xTable1.clearTreeExpand()'>折叠
              </vxe-button>
            </template>
          </vxe-toolbar>
          <div class='flex-app-continer-table-div'>
            <vxe-table
              style='overflow:auto;width: 100%;'
              height='auto' auto-resize
              size='mini'
              :show-header="false"
              transfer border show-header-overflow highlight-current-row show-overflow highlight-hover-row
              resizable
              ref='xTable1'
              :loadingTable1='loadingTable1'
              @cell-click='clickxTable1'
              :tree-config="{lazy: true,expandAll:true, children: 'children', hasChild:'hasChild', line: true,  loadMethod: loadChildrenMethod}"
              :data='tableData1'>
              <!--              <vxe-column align='center' header-align='center' type='checkbox' width='50'></vxe-column>-->
              <vxe-column align='left' header-align='center' field='title' title='企业/部门名称'
                          tree-node></vxe-column>
              <vxe-column width="70" align='right' field='staffNum' title=''>
                <template v-slot='{ row }'>
                  <template>
                    ({{ row.staffNum }})人
                  </template>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </div>
      </template>
      <template slot='paneR'>
        <div class='flex-app-continer-inner'>
          <vxe-form ref='form3' :data='formData3' @submit='queryDepartUser' size='mini' title-align='left'
                    title-width='50' style="margin-left: 5px;">
            <vxe-form-item title='姓名' field='realname' :item-render="{}">
              <template v-slot>
                <vxe-input
                  v-model='formData3.realname'
                  placeholder='请输入姓名回车查询'
                  clearable
                ></vxe-input>
              </template>
            </vxe-form-item>
            <vxe-form-item title='手机' field='phone' :item-render="{}">
              <template v-slot>
                <vxe-input
                  v-model='formData3.phone'
                  placeholder='请输入手机回车查询'
                  clearable
                ></vxe-input>
              </template>
            </vxe-form-item>
            <vxe-form-item>
              <template v-slot>
                <vxe-button type="submit" status="primary">查询</vxe-button>
                <vxe-button type="reset">重置</vxe-button>
              </template>
            </vxe-form-item>
          </vxe-form>
          <div class='result' v-if='checkedUser.length>0'>
            已选：<span class='result-item' v-for="(item, index) in checkedUser" :data-id="item.userId" :key="index" @click='unchecked'>{{item.realname}}</span>
          </div>
          <div class='flex-app-continer-table-div'>
            <vxe-table
              style='overflow:auto;width: 100%;' :print-config='{}' :export-config='{}'
              height='auto'
              :row-config="{keyField: 'userId', isHover: true}"
              @cell-click='clickxTable2'
              auto-resize border ref='xTable3' resizable size='mini' show-header-overflow highlight-current-row
              stripe show-overflow highlight-hover-row header-align='center'
              :checkbox-config='{highlight:true,range:true,trigger:"cell",checkMethod: checkCheckboxMethod,checkRowKeys: selectedUser}'
              :loading='loadingTable3' :data='tableData3'
              @checkbox-change='checkClick'
            >
              <vxe-column align='center' type='checkbox' width='50'></vxe-column>
              <vxe-column align='center' type='seq' title='序号' width='60'></vxe-column>
              <vxe-column field='avatar' title='头像' width='70' align='center' header-align="center">
                <template v-slot='{ row }'>
                  <template>
                    <a-avatar v-if="row.avatar" :src="row.avatar"/>
                  </template>
                </template>
              </vxe-column>
              <vxe-column field='username' title='账号' width='120'></vxe-column>
              <vxe-column field='realname' title='姓名' width='120'></vxe-column>
              <vxe-column field='phone' title='电话' width='120' align='center' header-align="center"></vxe-column>
              <vxe-column field='roleNames' title='角色' width='120'></vxe-column>
              <vxe-column field='departName' title='部门' width='130'></vxe-column>
              <vxe-column field='workNo' title='员工编号' width='100' align='right'
                          header-align="center"></vxe-column>
            </vxe-table>
          </div>
          <vxe-pager
            border
            size='mini'
            :loading='loadingPager2'
            :current-page='tablePage2.currentPage'
            :page-size='tablePage2.pageSize'
            :page-sizes='[2,50,100,1000]'
            :total='tablePage2.totalResult'
            :layouts="[ 'PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total' ]"
            @page-change='handlePageChange2'
          >
          </vxe-pager>
        </div>
      </template>
    </split-pane>
  </div>
</template>
<script>
import splitPane from 'vue-splitpane'
import Depart from '@comp/sys/Depart'
import Depart1 from '@comp/sys/Depart1.vue'
import {postAction} from "@/api/manage.js";
import {mixin} from '@/utils/mixin.js'

export default {
  name: 'DepartUser',
  components: {
    splitPane, 
    Depart, Depart1
  },
  mixins: [mixin],
  props: {
    companyId: {
      type: String
    },
    companys: {
      type: Array
    },
    disableUser: {
      type: Array,
      default: []
    },
    defaultChecked: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      selectedUser: ["1491619377682493441"],
      checkedUser:[],
      departMap: {},
      companyId1: {
        companyId: '',
        companyName: ''
      },
      formData: {},
      formData2: {},
      formData3: {},
      loadingTable1: false,
      loadingTable3: false,
      tableData1: [],
      tableData3: [],
      loadingPager2: false,
      tablePage2: {
        currentPage: 1,
        pageSize: 50,
        totalResult: 0
      },
      selectUserName: '',
      selectUserId: '',
      selectUserDepartId: '',

    }
  },
  computed: {},
  methods: {
    setChecked(){
      let arr = this.tableData3;
      let arr1 = [];
      for(let i=0;i<arr.length;i++){
        this.checkedUser.map((citem,j) => {
          if(citem.userId == arr[i].userId){
            arr1.push(arr[i]);
          }
        });
      }
      this.$refs.xTable3.clearCheckboxRow()
      this.$refs.xTable3.setCheckboxRow(arr1, true)
    },
    unchecked(e){
      let dataset = e.target.dataset;
      this.checkedUser.map((citem,i) => {
        if(citem.userId == dataset.id){
          this.checkedUser.splice(i,1);
        }
      });
      this.setChecked();
    },
    checkClick(e){
      //checkedUser
      let row = e.row;
      if(e.checked==false){  //取消
        this.checkedUser.map((citem,i) => {
          if(citem.userId == row.userId){
            this.checkedUser.splice(i,1);
          }
        });
      }else{
        let flag = false;
        this.checkedUser.map(citem => {
          if(citem.userId == row.userId){
            flag = true;
          }
        });
        if(!flag){
          this.checkedUser.push(row);
        }
      }
    },
    //判断是否可选择
    checkCheckboxMethod({row}) {
      for (let i = 0; i < this.disableUser.length; i++) {
        if (row.userId === this.disableUser[i].id) {
          return false;
        }
      }
      return true;
    },
    getData() {
      //return this.$refs.xTable3.getCheckboxRecords()
      return this.checkedUser
    },
    handlePageChange2(page) {
      this.tablePage2.currentPage = page.currentPage
      this.tablePage2.pageSize = page.pageSize
      this.queryDepartUser()
    },

    clickxTable1({row}) {
      this.tablePage2.currentPage = 1
      this.queryDepartUser()
    },
    clickxTable2({row}) {
    },
    async queryDepartUser() {
      let selectDeparts = this.$refs.xTable1.getCurrentRecord()
      if (selectDeparts && selectDeparts.id) {
        let params = {}
        params.realname = this.formData3.realname
        params.phone = this.formData3.phone
        if (params.realname || params.phone) {
          params.companyId = this.companyId
        } else {
          params.companyId = this.companyId
          params.departCode = selectDeparts.id
        }
        params.pageNo = this.tablePage2.currentPage;
        params.pageSize = this.tablePage2.pageSize
        this.tableData3 = []
        this.loadingTable3 = true
        await postAction('/sys/user/queryDepartUser', params).then(
          (res) => {
            this.loadingTable3 = false
            if (res.code === '0') {
              this.tableData3 = res.result.records
              if (this.tableData3 && this.tableData3.length) {
                this.tablePage2.totalResult = Number(res.result.total)
                this.$refs.xTable3.setCurrentRow(this.tableData3[0])
                this.clickxTable2({row: this.tableData3[0]})
              }
              this.setChecked();
            }
          }, (err) => {
            this.loadingTable3 = false
          }
        )
      }
    },

    async querySubDept(value, $event) {
      let that = this
      this.tableData1 = []
      let params = {}
      params.companyId = this.companyId
      params.departName = this.formData2.departName
      if (!params.departName) {
        // params.self = this.companys.find(value1 => value1.companyId === this.companyId).departCode;
        //只查出自己
        params.self = true
      }
      //   params.type = 'all'
      this.departMap = new Map()
      await postAction('/sys/user/querySubDepart', params).then(
        (res) => {
          if (res.code === '0') {
            this.tableData1 = res.result
            if (this.tableData1.length > 0) {
              this.$refs.xTable1.setCurrentRow(this.tableData1[0])
              this.clickxTable1({row: this.tableData1[0]})
              this.tableData1.map((item, index) => {
                that.departMap.set(item.id, item.name)
              })
            }
          }
        }, (err) => {
        }
      )
    },
    async loadChildrenMethod({row}) {
      let that = this
      let params = {}
      params.key = row.id
      let data = []
      await postAction('/sys/user/querySubDepart', params).then(
        (res) => {
          if (res.code === '0') {
            data = res.result
            if (data.length) {
              data.map((item, index) => {
                that.departMap.set(item.id, item.name)
              })
            }
          }
        }, (err) => {
        }
      )
      return Promise.resolve(data)
    },

  },
  mounted() {
  },
  created() {
    this.querySubDept()
  },
  watch: {
    userinfo: {
      handler(newV, oldV) {
        if (newV && newV.userDepart) {
        }
      },
      deep: true, // 是否深度监听，意为对象dataobj内部任何属性发生变化则全局重新渲染
      immediate: true // 代表在watch里声明了dataobj这个方法之后立即先去执行handler方法
    },
    defaultChecked: {
      handler(newV, oldV) {
        if (newV && newV.length>0) {
          this.checkedUser = newV
        }
      },
      deep: true, // 是否深度监听，意为对象dataobj内部任何属性发生变化则全局重新渲染
      immediate: true // 代表在watch里声明了dataobj这个方法之后立即先去执行handler方法
    }
  }

}
</script>
<style lang='scss' scoped>
.result{padding:10px;}
.result-item{cursor: pointer; position: relative; padding:0 15px;padding-right:30px; height: 30px;display:inline-block; line-height: 28px;border-radius: 5px;border: 1px solid #dcdfe6;text-align: center;font-size: 14px;color: #606266;margin-right:10px;}
.result-item:after{content:"";display: block;width: 15px;height: 15px;position: absolute;top:50%;margin-top:-7px;right:6px; background: url('../../assets/home/close.png');background-size:15px 15px;}
p {
  &.tip {
    border-left: 4px solid #41C7C0;
    padding: 5px 5px 5px 10px;
    margin: 5px 0;
    background-color: #f8f8f8;
  }
}

.my-dropdown1 {
  width: 500px;
  height: 100vh;
  background-color: #fff;
  box-shadow: 0 0 6px 2px rgba(0, 0, 0, 0.1);
}
</style>